package com.google.code.sms.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.google.code.sms.command.SearchCommand;
import com.google.code.sms.domain.SearchCriteria;
import com.google.code.sms.domain.SearchResult;
import com.google.code.sms.domain.User;
import com.google.code.sms.service.PlayerService;
import com.google.code.sms.service.SecurityService;
import com.google.code.sms.service.SettingsService;
import com.google.code.sms.service.SearchService;

/**
 * Controller for the search page.
 *
 * @author Sindre Mehus
 */
public class SearchController extends SimpleFormController {

    private static final int MATCH_COUNT = 25;
    private SecurityService securityService;
    private PlayerService playerService;
    private SearchService searchService;

    @Override
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        return new SearchCommand();
    }

    @Override
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object com, BindException errors)
            throws Exception {
        SearchCommand command = (SearchCommand) com;

        User user = securityService.getCurrentUser(request);
        command.setUser(user);

        String any = StringUtils.trimToNull(command.getQuery());

        if (any != null) {

            SearchCriteria criteria = new SearchCriteria();
            criteria.setCount(MATCH_COUNT);
            criteria.setQuery(any);

            SearchResult audioElements = searchService.search(criteria, SearchService.IndexType.AUDIO_ELEMENT);
            command.setAudioElements(audioElements.getMediaElements());

            SearchResult videoElements = searchService.search(criteria, SearchService.IndexType.VIDEO_ELEMENT);
            command.setVideoElements(videoElements.getMediaElements());

            SearchResult directoryElements = searchService.search(criteria, SearchService.IndexType.DIRECTORY_ELEMENT);
            command.setDirectoryElements(directoryElements.getMediaElements());

            command.setPlayer(playerService.getPlayer(request, response));
        }

        return new ModelAndView(getSuccessView(), errors.getModel());
    }

    public void setSecurityService(SecurityService securityService) {
        this.securityService = securityService;
    }

    public void setPlayerService(PlayerService playerService) {
        this.playerService = playerService;
    }

    public void setSearchService(SearchService searchService) {
        this.searchService = searchService;
    }
}
